﻿using ConfExpert.Forms.Base;
using DevExpress.XtraPivotGrid;
using DevTeam;

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Espresso
{
    public partial class Perf : XForm
    {
        public Perf()
        {
            InitializeComponent();
        }

        private void Perf_Load(object sender, EventArgs e)
        {
            
            this.
            RefreshData();
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);
            btnExport.ItemClick += btnExport_ItemClick;

            pvg.OptionsPrint.PrintColumnHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintDataHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintFilterHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.MergeRowFieldValues = false;
            pvg.OptionsPrint.MergeColumnFieldValues = false;
        }

        void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
         ExportPivot(pvg);
        }

        BindingSource bs;
        void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.Focused)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
        }


        void RefreshData()
        {
            bs = gridView1.Init("GetEspPerf");
            gridView1.Columns["CikilanCustomerId"].ColumnEdit = RI(Rp.V_Customer);
            gridView1.Columns["CikilanBrandId"].ColumnEdit = RI(Rp.Brand);
            gridView1.FormatAsNumber(0, "Qty");
            gridView1.FormatAsDate("CikisTarihi");
            gridView1.AddSummary("Qty");
            gridView1.OptionsBehavior.Editable = false;

            InitPivot(pvg, bs);

            //GetDetails("xOrdine", "Get7cOrdine", CKBatchId);
            //gridView1.Columns["idx"].Visible = 
            //gridView1.Columns["CodCliente"].Visible = false;
            pvg.Cells.Selection = new Rectangle(new Point(0, 0), new Size(1, 1));
            //pvg.Fields["Product"].BestFit();
            pvg.BestFit();
        }

        ImageList imageList1;
        bool PivotInitialized = false;
        void InitPivot(PivotGridControl pgc, BindingSource bs)
        {
            pgc.DataSource = bs;

            if (!PivotInitialized)
            {
                //imageList1 = new ImageList();
                //imageList1.ImageSize = new Size(32, 32);
                //imageList1.ColorDepth = ColorDepth.Depth16Bit;

                //foreach (DataRow dr in gridView1.Dataset().Tables[1].Rows)
                //    if (!AppSession.Lookups.V_Kumas.FindByProductId((int)dr["ProductId"]).IsPhotoMikroNull())
                //        imageList1.Images.Add(AppSession.Lookups.V_Kumas.FindByProductId((int)dr["ProductId"]).Name,
                //            byteArrayToImage(AppSession.Lookups.V_Kumas.FindByProductId((int)dr["ProductId"]).PhotoMikro));

                //pgc.ValueImages = imageList1;
                //pgc.FieldValueImageIndex += pgc_FieldValueImageIndex;

                pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
                pgc.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);
                pgc.CellSelectionChanged += new EventHandler(pgc_CellSelectionChanged);
                pgc.FocusedCellChanged += new EventHandler(pgc_FocusedCellChanged);
                pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
                pgc.CustomAppearance += new PivotCustomAppearanceEventHandler(pivotGridControl1_CustomAppearance);

                pgc.BeginUpdate();

                //new field - toplam tutar  (metre x fiyat+dvz cinsi)

                //AddNewField(pgc, "DosyaNo", PivotArea.FilterArea);
                //AddNewField(pgc, "CodCliente", PivotArea.FilterArea);
                //AddNewField(pgc, "Linea", PivotArea.FilterArea);
                //AddNewField(pgc, "Tex", PivotArea.FilterArea);

                //AddNewField(pgc, "ProductId", PivotArea.RowArea).Visible = false;   //.FieldEdit = RI(Rp.V_Kumas);
                PivotGridField pp = AddNewField(pgc, "ProductId", PivotArea.FilterArea);
                pp.FieldEdit = RI(Rp.V_Kumas);

                //PivotGridFieldBase[] pgf1 = new PivotGridFieldBase[3];
                //pgf1[0] = AddNewField(pgc, "Linea", PivotArea.RowArea);
                //pgf1[1] = AddNewField(pgc, "Modello", PivotArea.RowArea);
                //pgf1[1].ExpandedInFieldsGroup = false;
                //pgf1[2] = AddNewField(pgc, "Tex", PivotArea.RowArea);
                //pgc.Groups.Add(pgf1, "ModelloTex");

                PivotGridField pp2 = AddNewField(pgc, "CikilanBrandId", PivotArea.RowArea);
                pp2.FieldEdit = RI(Rp.Brand);
                //pp2.TopValueCount = 50;
                //pp2.TopValueType = PivotTopValueType.Absolute;
                //pp2.TopValueShowOthers = true;

                PivotGridField pqty = AddNewField(pgc, "Qty", PivotArea.DataArea);
                pqty.CellFormat.FormatString = "#,###";



                PivotGridField[] fields2 = new PivotGridField[2];
                //pivotGridControl1.Fields["Tarih"].ValueFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                //pivotGridControl1.Fields["Tarih"].ValueFormat.FormatString = "d";

                PivotGridField fieldYear = new PivotGridField("CikisTarihi", PivotArea.ColumnArea);
                PivotGridField fieldMonth = new PivotGridField("CikisTarihi", PivotArea.ColumnArea);

                // Add the fields to the field collection.
                pgc.Fields.Add(fieldYear);
                fieldYear.GroupInterval = PivotGroupInterval.DateYear;
                fieldYear.Caption = "Year";

                pgc.Fields.Add(fieldMonth);
                fieldMonth.GroupInterval = PivotGroupInterval.DateQuarter;
                fieldMonth.Caption = "Quarter";

                fields2[0] = fieldYear;
                fields2[1] = fieldMonth;

                fields2[0].ExpandedInFieldsGroup = false;
                pgc.Groups.Add(fields2, "CikisTarihi");

                fields2 = new PivotGridField[1];
                fields2[0] = AddNewField(pgc, "CikisTipiId", PivotArea.FilterArea);
                fields2[0].FieldEdit = RI(Rp.HareketTipi);

                pp2.SortBySummaryInfo.FieldName = "Qty";
                pp2.SortOrder = PivotSortOrder.Descending;

                //PivotGridFieldBase.GroupInterval

                //.Width = 40;  .Visible = true;
                //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

                foreach (PivotGridField pgf in pgc.Fields)
                {
                    pgf.SortOrder = PivotSortOrder.Descending;
                    pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
                }
                pgc.EndUpdate();

                PivotInitialized = true;
            }
        }


        void pgc_FieldValueImageIndex(object sender, PivotFieldImageIndexEventArgs e)
        {
            if (e.Field != null)
                if (e.Field.FieldName == "Product")
                    if (imageList1.Images.ContainsKey(e.Value.ToString()))
                        e.ImageIndex = imageList1.Images.IndexOfKey(e.Value.ToString());
        }

        void pgc_FocusedCellChanged(object sender, EventArgs e)
        {
            CellChanged();
        }


        void pgc_CellSelectionChanged(object sender, EventArgs e)
        {
            CellChanged();
        }

        private void CellChanged()
        {
            double PivotSum = 0.0;

            if (pvg.Cells.MultiSelection.SelectedCells.Count > 0)
            {
                foreach (Point cell in pvg.Cells.MultiSelection.SelectedCells)
                {
                    DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pvg.Cells.GetCellInfo(cell.X, cell.Y);
                    if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                        cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                        PivotSum += Convert.ToDouble(pvg.GetCellValue(cell.X, cell.Y));
                }
            }
            else
            {
                DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pvg.Cells.GetFocusedCellInfo();
                if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                    cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                    PivotSum += Convert.ToDouble(pvg.GetCellValue(pvg.Cells.FocusedCell.X, pvg.Cells.FocusedCell.Y));

            }
            lbl.Caption = PivotSum == 0 ? string.Empty : String.Format("{0:#,##0.## mt'.'}", PivotSum);
        }

        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gridControl1.DataSource = e.CreateDrillDownDataSource();
            ExpandCollapse(splitContainerControl1, (gridView1.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView1.BestFitColumns();
            gridView1.MoveFirst();
        }
    }
}
